package com.store.framework.rest;

import java.util.List;
import java.util.UUID;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.store.framework.entry.AppRoot;
import com.store.framework.logic.IAppRootLogic;
import com.store.framework.logic.imp.AppRootLogic;
@Path("AdRootService")
public class AdRootService {
	IAppRootLogic approot = new AppRootLogic();
	private static Log LOG = LogFactory.getLog(AdRootService.class);

	@POST
	@Path("addRoot")
	@Produces("application/json; charset=UTF-8")
	public String AddRoot(String input) {
		LOG.debug(input);
		JSONObject jb = JSONObject.fromObject(input);
		@SuppressWarnings("static-access")
		AppRoot ar = (AppRoot) jb.toBean(jb, AppRoot.class);
		String key = UUID.randomUUID().toString();
		ar.setId(key);
		
		int row = 0;
		String msg = "";
		try {
			row = approot.Add(ar);
			if(row == 1){
				msg =  "{\"success\":true,\"id\":\""+key+"\"}";
			}
		} catch (Exception e) {
			msg = "{\"success\":false,errorMsg:\""+e.getMessage()+"\"}";
		}
		return msg;
	}

	@POST
	@Path("selectRoot")
	@Produces("application/json; charset=UTF-8")
	public String selectRoot(
			@FormParam("start") Long start,
			@FormParam("limit") Long limit) {
		int count = approot.getCount();
		List<AppRoot> list = approot.select(start,limit);
		JSONArray ja = JSONArray.fromObject(list);
		return "{\"totalProperty\":"+count+",\"root\":"+ja.toString()+"}";

	}

	
	
	@POST
	@Path("deleteRoot")
	@Produces("application/json; charset=UTF-8")
	public String deleteRoot(String id) {
		AppRoot at = new AppRoot();
		at.setId(id);
		approot.delete(at);
		return "{\"result\":1}";
	}
	
	
	@POST
	@Path("updateRoot")
	@Produces("application/json; charset=UTF-8")
	public String updateRoot(String input) {
		LOG.debug(input);
		JSONObject jo = JSONObject.fromObject(input);
		@SuppressWarnings("static-access")
		AppRoot at = (AppRoot) jo.toBean(jo, AppRoot.class);
		int row = 0;
		String msg = "";
		try {
			row = approot.update(at);
			if(row == 1){
				msg = "{\"success\":true}";
			}
		} catch (Exception e) {
			msg = "{\"success\":false,errorMsg:\""+e.getMessage()+"\"}";
		}	
		return msg;
	}
	
	public static void main(String[] args) {
//		new AdRoot().selectRoot();
	}
}
